package com.ctg.itrdc.imageconsole.control.ssh.utils;

import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ctg.itrdc.imageconsole.common.util.PropertiesUtils;


public class DSPool {

    private static Logger log = LoggerFactory.getLogger(DSPool.class);

    private static PoolingDataSource dsPool;
    private static boolean TEST_ON_BORROW = Boolean.valueOf(AppConfig.getProperty("testOnBorrow"));
    private static int MIN_IDLE = Integer.parseInt(AppConfig.getProperty("minIdle"));
    private static int MAX_WAIT = Integer.parseInt(AppConfig.getProperty("maxWait"));
    private static int MAX_ACTIVE = Integer.parseInt(PropertiesUtils.getConfigValue("conf/jdbc", "jdbc.maxActive"));
    
    private static String mysqladd = PropertiesUtils.getConfigValue("conf/jdbc", "jdbc.url");
    private static String mysqluser = PropertiesUtils.getConfigValue("conf/jdbc", "jdbc.username");
    private static String mysqlpsw = PropertiesUtils.getConfigValue("conf/jdbc", "jdbc.password");

    private DSPool() {
    }


    /**
     * fetches the data source for H2 db
     *
     * @return data source pool
     */

    public static org.apache.commons.dbcp.PoolingDataSource getDataSource() {
        if (dsPool == null) {

            dsPool = registerDataSource();
        }
        return dsPool;
    }

    /**
     * register the data source for H2 DB
     *
     * @return pooling database object
     */

    private static PoolingDataSource registerDataSource() {
        String validationQuery = "select 1";
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            log.error(ex.toString(), ex);
        }
        GenericObjectPool connectionPool = new GenericObjectPool(null);

        connectionPool.setMaxActive(MAX_ACTIVE);
        connectionPool.setTestOnBorrow(TEST_ON_BORROW);
        connectionPool.setMinIdle(MIN_IDLE);
        connectionPool.setMaxWait(MAX_WAIT);
        connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);

        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(mysqladd, mysqluser, mysqlpsw);
        new PoolableConnectionFactory(connectionFactory, connectionPool, null, validationQuery, false, true);

        return new PoolingDataSource(connectionPool);
    }

}

